package com.itrip.service.impl;

import com.itrip.dao.ItripHotelOrderMapper;
import com.itrip.dao.ex.OrderMapperEX;
import com.itrip.dao.ex.TempStoreMapperEX;
import com.itrip.dto.OrderListDTO;
import com.itrip.dto.OrderPayDTO;
import com.itrip.pojo.ItripHotelOrder;
import com.itrip.service.OrderService;
import com.itrip.vo.order.OrderCountVO;
import com.itrip.vo.order.OrderListVO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private ItripHotelOrderMapper orderMapper;

    @Resource
    private ItripHotelOrderMapper hotelOrderMapper;

    @Resource
    private OrderMapperEX orderMapperEX;

    @Resource
    private TempStoreMapperEX tempStoreMapperEX;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    @Transactional(rollbackFor = Exception.class)

    @Override
    public int addOrder(ItripHotelOrder order) {
        int countOrder = orderMapper.insertSelective(order);
        int countStore = 0;
        if(countOrder > 0) {
            //订单创建成功，扣减库存
            //需要扣减的库存
            int storeSub = order.getCount();
            //对应的房间id
            Long roomId = order.getRoomId();

            //添加最新库存信息
            countStore = tempStoreMapperEX.addStore(roomId, storeSub);

            //存储订单ID，房间ID，扣减的库存到Redis，有效期30分钟
            redisTemplate.opsForValue().set("order:"+order.getId()+","
                    +order.getRoomId()+"," +storeSub,order.getUserId(),30, TimeUnit.MINUTES);

        }

            return countStore;

    }

    @Override
    public int getCountByUser(Long userId) {
        return orderMapperEX.getCountByUser(userId);
    }

    @Override
    public OrderPayDTO getOrderPayByUser(Long userId) {
        return orderMapperEX.getOrderPayByUser(userId);
    }

    @Override
    public List<OrderListDTO> getOrderListByParams(OrderListVO orderListVO, Long userId, int start) {
        return orderMapperEX.getOrderListByParams(orderListVO,userId,start);
    }

    @Override
    public int getOrderCountByParams(OrderCountVO orderCountVO, Long userId) {
        return orderMapperEX.getOrderCountByParams(orderCountVO,userId);
    }

    @Override
    public int getOrderStatus(long orderId) {
        return orderMapperEX.getOrderStatus(orderId);
    }

    @Override
    public int updateOrderStatusInvalid(long orderId) {
        return orderMapperEX.updateOrderStatusInvalid(orderId);
    }

    @Override
    public int deleteOrderById(Long id) {
        return hotelOrderMapper.deleteByPrimaryKey(id);
    }

}
